<template>
  <el-dialog
    v-model="dialogVisible"
    width="480"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    :show-close="false"
    @close="closeDialog"
  >
    <template #header>
      <p><i class="icon"></i>上传发票</p>
    </template>
    <el-upload
      class="upload-demo"
      ref="uploadImg"
      :show-file-list="false"
      drag
      multiple
      :auto-upload="false"
      :on-change="
        (file, fileList) => {
          handleAvatarChangeIcon(file, fileList);
        }
      "
    >
      <div class="jzt-flex-center">
        <el-icon class="mb0 mr10" style="width: 20px">
          <img src="@/assets/images/upload.png" alt="" width="20" />
        </el-icon>
        <div style="color: #007dff"><span style="line-height: 24px">上传文件</span></div>
      </div>

      <p style="color: #86909c">支持扩展名doc/docx/pdf/jpg/png</p>
    </el-upload>
    <div class="file-list mt22">
      <div class="list-item" v-for="(item, index) in FileList" :key="index">
        <div class="left">
          <img v-if="item.img" :src="getUrl(item.img)" alt="" />
          <el-icon class="img" v-else><Loading /></el-icon>
          <div class="ml10 text-over" style="flex: 1">
            <p class="text-over" :title="item.name">{{ item.name }}</p>
          </div>
        </div>

        <el-icon class="close-icon" @click="delFileList(item, index)"><CircleCloseFilled /></el-icon>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="info" class="jzt-button" @click="closeDialog">取消</el-button>
        <el-button :disabled="optionInfo.type === 'add' && !imgIsReady" type="primary" @click="submit"> 确认上传 </el-button>
        <!-- <el-button type="primary" @click="submit">确认上传</el-button> -->
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from "vue";
import useMultipartOssStore from "@/store/modules/multipartOssStore.js";
const ossStore = useMultipartOssStore();
import { ElMessage } from "element-plus";
import { _debounce, getFileSuffix } from "@/utils/index"; //防抖，多次频繁触发时，只执行最后一次
import { CloseBold, Loading, CircleCloseFilled } from "@element-plus/icons-vue";
import { getFolder } from "@/utils/index";
import excel from "@/assets/images/excel.png";
import word from "@/assets/word.png";
import pdf from "@/assets/pdf.png";

const emit = defineEmits(["submit", "close"]);
const props = defineProps({
  optionInfo: {
    type: Object,
    default: () => {
      return {
        isShow: false,
        type: "add", // add edit
        list: []
      };
    }
  }
});
const dialogVisible = ref(false);
const FileList = ref([]);
const editFileList = ref([]);
const uploadImg = ref();

watch(
  () => props.optionInfo,
  val => {
    dialogVisible.value = val.isShow;
    console.log("AAAAAAAAAA", val);
    if (val.isShow && val.type === "edit") {
      FileList.value = [...val.list];
      editFileList.value = [...val.list];
    } else {
      FileList.value = [];
      editFileList.value = [];
    }
  },
  { deep: true }
);

const getUrl = url => {
  const fileArr = ["doc", "docx"];
  const excelArr = ["xls", "xlsx"];
  const fileSuffix = getFileSuffix(url).toLowerCase() || "";
  const type = fileArr.includes(fileSuffix)
    ? "doc"
    : excelArr.includes(fileSuffix)
      ? "excel"
      : fileSuffix === "pdf"
        ? "pdf"
        : "img";
  return type === "doc" ? word : type === "excel" ? excel : type === "pdf" ? pdf : url;
};

const closeDialog = () => {
  //   resetForm(); //清空表单
  uploadImg.value.clearFiles();
  FileList.value = [];
  imgIsReady.value = false;
  emit("close");
};
const submit = async () => {
  // for (let i = 0; i < FileList.value.length; i++) {
  //   if (!FileList.value[i].linkUrl) {
  //     return ElMessage({
  //       message: "请完整填写链接地址",
  //       type: "error"
  //     });
  //   }
  // }

  console.log("编辑时的文件列表===", FileList.value);
  emit("submit", FileList.value);
  uploadImg.value.clearFiles();
  FileList.value = [];
  imgIsReady.value = false;
};

//====================================图片上传========================================================================================

const imgIsReady = ref(false);
const handleAvatarChangeIcon = _debounce(async (file, fileList, type = "file") => {
  //选中文件触发的change事件
  console.log("触发文件上传", fileList);
  imgIsReady.value = false;

  const flag = await fileType(type, type === "file" ? fileList : [file]);
  if (!flag) {
    const errorFile = [];
    const successFile = [];
    if (type === "file") {
      ElMessage({
        message: "只支持扩展名doc/docx/pdf/jpg",
        type: "error",
        offset: 60
      });
      for (let item of fileList) {
        if (
          !(
            item.raw.type === "image/jpeg" ||
            item.raw.type === "image/png" ||
            item.raw.type === "application/msword" ||
            item.raw.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
            item.raw.type === "application/pdf" ||
            item.raw.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
            item.raw.type === "application/vnd.ms-excel"
          )
        ) {
          errorFile.push(item);
        } else {
          successFile.push(item);
        }
      }
      for (let item of errorFile) {
        uploadImg.value.handleRemove(item);
      }
    }
    if (successFile.length <= 0) return;
  }

  FileList.value = [...editFileList.value, ...fileList];
  // console.log("准备上传的文件", FileList.value);
  const _ready = FileList.value.filter(item => item.status === "ready");
  for (let item of _ready) {
    await customUpload(item, { file: item });
  }
  const imgArr = _ready.map(item => {
    if (item.img) {
      return item.img;
    }
  });
  if (imgArr.length === _ready.length) {
    imgIsReady.value = true;
  } else {
    imgIsReady.value = false;
  }
}, 100);
/**
 * 校验文件类型
 */
const fileType = async (type, fileList) => {
  let flag = true;
  if (type === "file") {
    for (let item of fileList) {
      if (
        !(
          item.raw.type === "image/jpeg" ||
          item.raw.type === "image/png" ||
          item.raw.type === "application/msword" ||
          item.raw.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
          item.raw.type === "application/pdf" ||
          item.raw.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
          item.raw.type === "application/vnd.ms-excel"
        )
      ) {
        flag = false;
      }
    }
  }
  return flag;
};
/**
 * 获取视频时间长度
 */
const videoTime = ref(0);
const getTimes = async file => {
  let content = file;
  //获取录音时长
  let url = URL.createObjectURL(content);
  //经测试，发现audio也可获取视频的时长
  let audioElement = new Audio(url);
  console.log(2222);
  await new Promise((resolve, reject) => {
    audioElement.addEventListener("loadedmetadata", _event => {
      //保存获取时间长度
      videoTime.value = parseInt(audioElement.duration);
      resolve("时长获取成功");
    });
  });
};
/**
 * 上传
 */
const getFileName = name => {
  const arr = name.split(".");
  const _arr = JSON.parse(JSON.stringify(arr));
  let _name = "";
  let _suffix = "";
  if (arr.length > 2) {
    _arr.splice(_arr.length - 1, 1);
    _name = _arr.join(".");
    _suffix = arr[arr.length - 1];
  } else {
    _name = arr[0];
    _suffix = arr[1];
  }
  const folder = getFolder();
  return folder + _name + new Date().getTime() + "." + _suffix;
};
const customUpload = async (item, option) => {
  // 合并已上传和当前上传文件
  const objName = getFileName(option.file.name);
  await ossStore
    .submit(objName, option.file.raw)
    .then(async res => {
      await ossStore.setACL(objName, fileReadRole.publicRead);
      res.fileUrl = await ossStore.signatureUrl(objName);
      console.log("文件上传成功，地址为===", res.fileUrl);
      item["img"] = res.fileUrl.split("?")[0];
      item["folder"] = objName;
    })
    .catch(err => {
      alert(JSON.stringify(err));
    });
};
const fileReadRole = {
  defaultRole: "",
  privateRole: "private",
  publicRead: "public-read",
  publicReadWrite: "public-read-write"
};
const getLocalUrl = file => {
  if (!file?.raw) return "";
  return URL.createObjectURL(file.raw);
};
const delFileList = (item, index) => {
  FileList.value.splice(index, 1);
  if (item.status === "success") {
    editFileList.value.splice(index, 1);
  } else {
    uploadImg.value.handleRemove(item);
  }
};
</script>

<style lang="scss" scoped>
p {
  margin: 0;
}
:deep(.el-upload-dragger) {
  background-color: #f2f3f5;
  padding: 10px;
  border-color: #c0c4cc;
}
.el-icon--upload {
  height: auto;
  margin-bottom: 10px;
}
.file-list {
  display: grid;
  gap: 20px;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  .list-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-radius: 0px 0px 0px 0px;
    border: 1px solid #eaecf0;
    border-radius: 4px;
    padding: 8px 10px;
    position: relative;
    .left {
      width: 100%;
      display: flex;
      align-items: center;
    }
    :deep(.close-icon.el-icon) {
      position: absolute;
      top: -6px;
      right: -6px;
      color: #ff3333;
    }
    img,
    .img {
      width: 24px;
      height: 24px;
      border-radius: 50%;
      vertical-align: bottom;
      font-size: 24px;
    }
  }
}
</style>
